import 'dart:collection';

import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../../common/model/model.dart';
import '../../list/index.dart';
import 'package:lunar/calendar/Lunar.dart';
import 'package:lunar/calendar/Solar.dart';

final kEvents = LinkedHashMap<DateTime, List<EventRecord>>(
  equals: isSameDay,
  hashCode: getHashCode,
)..addAll(init());

Map<DateTime, List<EventRecord>> init() {
  ListController listController = Get.find();
  List<EventRecord> eventRecords = listController.state.eventRecords;
  return valuesByFirstName(eventRecords);
}

// 根据分类分组
Map<DateTime, List<EventRecord>> valuesByFirstName(List<EventRecord> values) {
  Map<DateTime, List<EventRecord>> result = {};
  for (EventRecord val in values) {
    DateTime frtDateTime = formatDateDay(val.date!, lunar: val.lunar!);

    if (result[frtDateTime] != null) {
      result[frtDateTime]!.add(val);
    } else {
      result[frtDateTime] = [val];
    }
  }
  return result;
}

//传入时间。格式化成今年的日期
DateTime formatDateDay(DateTime from, {bool lunar = false}) {
  DateTime today = DateTime.now();
  today = DateTime(today.year, today.month, today.day);
  //用户今年阳历生日 如果过了会计算明年的
  DateTime userToEewYear = from;

  //不是阳历直接处理
  if (!lunar) {
    //如果是
    Solar todaySolarDate = Solar.fromDate(from);
    //取今年阳历
    var solar = Solar.fromYmd(
        today.year, todaySolarDate.getMonth(), todaySolarDate.getDay());
    userToEewYear =
        DateTime.utc(solar.getYear(), solar.getMonth(), solar.getDay());
    return userToEewYear;
  }
  //农历处理
  if (lunar) {
    Lunar todayLunarDate = Lunar.fromDate(today);
    Solar todaySolarDate = Solar.fromDate(today);

    int year = 0;
    if (todayLunarDate.getYear() == todaySolarDate.getYear()) {
      year = todaySolarDate.getYear();
    }
    if (todayLunarDate.getYear() < todaySolarDate.getYear()) {
      year = todayLunarDate.getYear();
    }

    //1.获取用户农历日期
    Lunar lunarDate = Lunar.fromDate(from);
    //查询今年农历转阳历
    var solar = Lunar.fromYmd(year, lunarDate.getMonth(), lunarDate.getDay())
        .getSolar();
    //2.转阳历
    userToEewYear =
        DateTime.utc(solar.getYear(), solar.getMonth(), solar.getDay());
    return userToEewYear;
  }
  return userToEewYear;
}

int getHashCode(DateTime key) {
  return key.day * 1000000 + key.month * 10000 + key.year;
}

List<DateTime> daysInRange(DateTime first, DateTime last) {
  final dayCount = last.difference(first).inDays + 1;
  return List.generate(
    dayCount,
    (index) => DateTime.utc(first.year, first.month, first.day + index),
  );
}

final kToday = DateTime.now();
final kFirstDay = DateTime(kToday.year, kToday.month - 3, kToday.day);
final kLastDay = DateTime(kToday.year, kToday.month + 3, kToday.day);
